package com.itheima.app.manager;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.Question;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.RecommendUser;
import com.itheima.domain.mongo.Visitor;
import com.itheima.service.db.QuestionService;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.RecommendUserService;
import com.itheima.service.mongo.UserLocationService;
import com.itheima.service.mongo.VisitorService;
import com.itheima.util.ConstantUtil;
import com.itheima.vo.NearUserVo;
import com.itheima.vo.PageBeanVo;
import com.itheima.vo.RecommendUserVo;
import com.itheima.vo.VisitorVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import javax.xml.stream.util.StreamReaderDelegate;
import java.util.ArrayList;
import java.util.List;

@Component
public class MakeFriendManager {
    @DubboReference
    private RecommendUserService recommendUserService;
    @DubboReference
    private UserInfoService userInfoService;
    @DubboReference
    private QuestionService questionService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @DubboReference
    private VisitorService visitorService;
    @DubboReference
    private UserLocationService userLocationService;
   //今日佳人
    public ResponseEntity findTodayBest() {
        Long toUserId = UserHolder.get().getId();
        //调用业务层根据被推荐用户id查询出今日佳人对象
        RecommendUser maxScoreRecommendUser = recommendUserService.findMaxScoreRecommendUser(toUserId);
        //根据返回值创建并封装vo类
        RecommendUserVo recommendUserVo = new RecommendUserVo();
        UserInfo userInfo = userInfoService.findById(maxScoreRecommendUser.getUserId());
        recommendUserVo.setUserInfo(userInfo);
        recommendUserVo.setFateValue(maxScoreRecommendUser.getScore().longValue());
        //返回页面
        return ResponseEntity.ok(recommendUserVo);
    }
   //推荐列表
    public ResponseEntity findRecommendation(Integer pageNum, Integer pageSize) {
        Long toUserId = UserHolder.get().getId();
        //调用业务层根据被推荐用户id、当前页和页大小查询出推荐列表分页类
        PageBeanVo pageBeanVo = recommendUserService.findRecommendUserByPage(toUserId, pageNum, pageSize);
        //根据返回值创建并封装vo集合
        List<RecommendUserVo> recommendUserVos = new ArrayList<>();
        //取出推荐列表 判断非空 遍历
        List<RecommendUser> items = (List<RecommendUser>) pageBeanVo.getItems();
        if (CollectionUtil.isNotEmpty(items)) {
            for (RecommendUser item : items) {
                //根据推荐列表中的userId查询出推荐人的详细信息
                UserInfo userInfo = userInfoService.findById(item.getUserId());
                //创建并封装vo类
                RecommendUserVo recommendUserVo = new RecommendUserVo();
                recommendUserVo.setUserInfo(userInfo);
                recommendUserVo.setFateValue(item.getScore().longValue());
                //把vo类添加到vo集合
                recommendUserVos.add(recommendUserVo);
            }
        }
        //把vo集合赋值给分页类
        pageBeanVo.setItems(recommendUserVos);
        //返回页面
        return ResponseEntity.ok(pageBeanVo);
    }
   //推荐用户详情
    public ResponseEntity findPersonalInfo(Long recommendUserId) {
        Long toUserId = UserHolder.get().getId();
        //定义推荐用户类
        RecommendUser recommendUser = null;
        //创建vo类
        RecommendUserVo recommendUserVo = new RecommendUserVo();
        //判断前端请求入口是哪个
        if (toUserId == recommendUserId) {
            // 我的动态 创建新推荐用户类
            recommendUser = new RecommendUser();
            //赋值推荐用户类
            recommendUser.setUserId(toUserId);
            recommendUser.setScore(100D);
        } else {
            //推荐用户详情 调用业务层根据推荐id和被推荐id查询出推荐用户
            recommendUser = recommendUserService.findRecommendUserByCondition(toUserId, recommendUserId);
        }
        //根据推荐用户的id查询出推荐用户的详情信息
        UserInfo userInfo = userInfoService.findById(recommendUser.getUserId());
        //给vo类赋值
        recommendUserVo.setUserInfo(userInfo);
        recommendUserVo.setFateValue(recommendUser.getScore().longValue());
        //返回页面
        return ResponseEntity.ok(recommendUserVo);
    }
    //（聊一下）查看陌生人问题
    public ResponseEntity findStrangerQuestions(Long jiaRenId) {
        //调用业务层根据佳人id获取佳人问题
        Question question = questionService.findByUserId(jiaRenId);
        //如果为空创建默认值
        if (question == null) {
            question = new Question();
        }
        //返回页面
        return ResponseEntity.ok(question.getStrangerQuestion());
    }
    //查询最近访客
    public ResponseEntity findVisitors() {
        Long userId = UserHolder.get().getId();
        //获取redis的上次登录时间
        String lastTime = stringRedisTemplate.opsForValue().get(ConstantUtil.LAST_ACCESS_TIME + userId);
        //创建vo集合
        List<VisitorVo> visitorVos = new ArrayList<>();
        //如果有上次登录时间
        if (StrUtil.isNotEmpty(lastTime)) {
            //调用业务层查询访客列表（前五条）
            List<Visitor> visitors = visitorService.findVisitorByCondition(userId, Long.parseLong(lastTime));
            //如果列表不为空遍历封装vo 并添加到vo集合
            if (CollectionUtil.isNotEmpty(visitors)) {
                for (Visitor visitor : visitors) {
                    VisitorVo visitorVo = new VisitorVo();
                    visitorVo.setUserInfo(userInfoService.findById(visitor.getVisitorUserId()));
                    visitorVo.setFateValue(visitor.getScore().longValue());
                    visitorVos.add(visitorVo);
                }
            }
        }
        //记录本次登录时间
        stringRedisTemplate.opsForValue().set(ConstantUtil.LAST_ACCESS_TIME + userId, System.currentTimeMillis() + "");
        //返回vo集合
        return ResponseEntity.ok(visitorVos);
    }
   //上传地理位置
    public void uploadLocation(double latitude, double longitude, String addrStr) {
        Long userId = UserHolder.get().getId();
        //调用业务层保存
        userLocationService.uploadLocation(userId, longitude, latitude, addrStr);
    }
    //查询附近的人
    public ResponseEntity findSearch(String gender, String distance) {
        Long userId = UserHolder.get().getId();
        //调用业务层查询出满足条件的附近用户id的集合
        List<Long> searchIds = userLocationService.searchNearUserId(userId, Double.parseDouble(distance));
        //创建vo集合
        List<NearUserVo> nearUserVos=new ArrayList<>();
        //判断附近用户id集合是否非空 遍历
        if (CollectionUtil.isNotEmpty(searchIds)) {
            for (Long searchId : searchIds) {
                //如果用户id与附近用户id相等直接遍历下一个
                if (userId == searchId) {
                    continue;
                }
                //如果附近用户性别与用户选择的性别不同直接遍历下一个
                if (!gender.equals(userInfoService.findById(searchId).getGender())) {
                    continue;
                }
                //以下是满足条件的用户 创建vo类 赋值
                NearUserVo nearUserVo = new NearUserVo();
                nearUserVo.setNickname(userInfoService.findById(searchId).getNickname());
                nearUserVo.setAvatar(userInfoService.findById(searchId).getAvatar());
                nearUserVo.setUserId(searchId);
                //把vo类添加的vo集合
                nearUserVos.add(nearUserVo);
            }
        }
        //返回页面
        return ResponseEntity.ok(nearUserVos);
    }
    //探花卡片
    public ResponseEntity findCards() {
        Long userId = UserHolder.get().getId();
        //根据用户id和分页条件查询出推荐用户分页
        PageBeanVo pageBeanVo = recommendUserService.findRecommendUserByPage(userId, 1, 10);
        //创建vo集合
        List<RecommendUserVo> recommendUserVos=new ArrayList<>();
        //取出推荐用户 判断非空遍历
        List<RecommendUser> items = (List<RecommendUser>) pageBeanVo.getItems();
        if (CollectionUtil.isNotEmpty(items)) {
            for (RecommendUser item : items) {
                //根据推荐用户的id查询出推荐用户详情
                UserInfo userInfo = userInfoService.findById(item.getUserId());
                //创建vo类 赋值 并添加到vo集合
                RecommendUserVo recommendUserVo = new RecommendUserVo();
                recommendUserVo.setUserInfo(userInfo);
                recommendUserVos.add(recommendUserVo);
            }
        }//返回vo集合
        return ResponseEntity.ok(recommendUserVos);
    }
}
